<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#409EFF"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ formatCurrency(todayData?.mincomes || 0) }}</div>
              <div class="stat-label">今日收入</div>
              <div class="stat-yesterday">昨日: {{ formatCurrency(yesterdayData?.mincomes || 0) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="40" color="#F56C6C"><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ formatCurrency(todayData?.iprices || 0) }}</div>
              <div class="stat-label">今日成本</div>
              <div class="stat-yesterday">昨日: {{ formatCurrency(yesterdayData?.iprices || 0) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 周统计报表 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="week-stat-card">
          <template #header>
            <div class="card-header">
              <span>周统计报表</span>
              <el-button type="primary" @click="refreshWeekStat">刷新数据</el-button>
            </div>
          </template>
          <div ref="weekStatChart" style="width: 100%; height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { fetchWeekStatData, fetchTwoDayData } from '@/api/report'

// 两日数据相关
const todayData = ref<any>(null)
const yesterdayData = ref<any>(null)

// 周统计图表相关
const weekStatChart = ref<HTMLDivElement>()
let weekStatChartInstance: ECharts | null = null

// 周统计数据
const weekStatData = ref<any[]>([])

// 获取两日数据
const loadTwoDayData = async () => {
  try {
    const data = await fetchTwoDayData()
    if (data && data.length >= 2) {
      // 假设第一条是今天的数据，第二条是昨天的数据
      todayData.value = data[0]
      yesterdayData.value = data[1]
    }
  } catch (error) {
    console.error('获取两日数据失败:', error)
    // 如果API调用失败，使用模拟数据
    todayData.value = { dt: '2024-01-01', mincomes: 8901200, iprices: 4500000 }
    yesterdayData.value = { dt: '2023-12-31', mincomes: 8500000, iprices: 4200000 }
  }
}

// 格式化货币显示
const formatCurrency = (value: number) => {
  // 将价格除以100000，转换为元，保留两位小数
  const yuanValue = value / 100000
  return `¥${yuanValue.toFixed(2)}`
}

// 获取变化文本
const getChangeText = (todayValue: number, yesterdayValue: number, isCost = false) => {
  if (!todayValue || !yesterdayValue) return ''
  
  const change = todayValue - yesterdayValue
  const percent = Math.abs(change / yesterdayValue * 100).toFixed(1)
  
  if (change === 0) return '持平'
  
  if (isCost) {
    // 对于成本，减少是好的（positive），增加是坏的（negative）
    return change < 0 ? `↓${percent}%` : `↑${percent}%`
  } else {
    // 对于收入，增加是好的（positive），减少是坏的（negative）
    return change > 0 ? `↑${percent}%` : `↓${percent}%`
  }
}

// 初始化周统计图表
const initWeekStatChart = () => {
  if (!weekStatChart.value) return
  
  weekStatChartInstance = echarts.init(weekStatChart.value)
  
  const option = {
    title: {
      text: '周统计报表',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['请求量', '展示量', '点击量'],
      top: '10%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '20%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: weekStatData.value.map(item => item.dt),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '请求量',
        type: 'line',
        data: weekStatData.value.map(item => item.requests),
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '展示量',
        type: 'line',
        data: weekStatData.value.map(item => item.imps),
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '点击量',
        type: 'line',
        data: weekStatData.value.map(item => item.clicks),
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  weekStatChartInstance.setOption(option)
}

// 获取周统计数据
const loadWeekStatData = async () => {
  try {
    const data = await fetchWeekStatData()
    weekStatData.value = data
    
    // 更新图表数据
    if (weekStatChartInstance) {
      const option = {
        xAxis: {
          data: data.map(item => item.dt)
        },
        series: [
          { data: data.map(item => item.requests) },
          { data: data.map(item => item.imps) },
          { data: data.map(item => item.clicks) }
        ]
      }
      weekStatChartInstance.setOption(option)
    }
  } catch (error) {
    console.error('加载周统计数据失败:', error)
    // 如果API调用失败，使用模拟数据
    weekStatData.value = generateMockWeekData()
    if (weekStatChartInstance) {
      weekStatChartInstance.setOption({
        xAxis: {
          data: weekStatData.value.map(item => item.dt)
        },
        series: [
          { data: weekStatData.value.map(item => item.requests) },
          { data: weekStatData.value.map(item => item.imps) },
          { data: weekStatData.value.map(item => item.clicks) }
        ]
      })
    }
  }
}

// 生成模拟周数据
const generateMockWeekData = () => {
  const days = ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05', '2024-01-06', '2024-01-07']
  return days.map(day => ({
    dt: day,
    requests: Math.floor(Math.random() * 1000) + 100,
    imps: Math.floor(Math.random() * 800) + 50,
    clicks: Math.floor(Math.random() * 100) + 10
  }))
}

// 刷新周统计数据
const refreshWeekStat = () => {
  loadWeekStatData()
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (weekStatChartInstance) {
    weekStatChartInstance.resize()
  }
}

onMounted(() => {
  // 加载两日数据
  loadTwoDayData()
  
  // 加载周统计数据
  loadWeekStatData()
  
  // 初始化图表
  setTimeout(() => {
    initWeekStatChart()
  }, 100)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (weekStatChartInstance) {
    weekStatChartInstance.dispose()
  }
})
</script>

<style scoped>
/* 动画定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0);
  }
}

.dashboard-container {
  padding: 24px;
  min-height: calc(100vh - 80px);
  background: transparent;
  animation: fadeInUp 0.8s ease-out;
}

.stat-card {
  margin-bottom: 24px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(31, 38, 135, 0.37),
    0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  animation: slideInUp 0.8s ease-out;
}

.stat-card:nth-child(1) { animation-delay: 0.1s; }
.stat-card:nth-child(2) { animation-delay: 0.2s; }
.stat-card:nth-child(3) { animation-delay: 0.3s; }
.stat-card:nth-child(4) { animation-delay: 0.4s; }

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 
    0 12px 40px rgba(31, 38, 135, 0.5),
    0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px;
}

.stat-icon {
  flex-shrink: 0;
  margin-right: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.stat-icon:hover {
  transform: scale(1.1);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

.stat-info {
  flex: 1;
  text-align: right;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.stat-label {
  font-size: 16px;
  color: #64748b;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-yesterday {
  font-size: 14px;
  color: #94a3b8;
  margin-bottom: 8px;
}

.stat-change {
  font-size: 14px;
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-block;
  transition: all 0.3s ease;
}

.stat-change.positive {
  color: #10b981;
  background: rgba(16, 185, 129, 0.1);
}

.stat-change.negative {
  color: #ef4444;
  background: rgba(239, 68, 68, 0.1);
}

.stat-change:hover {
  transform: scale(1.05);
}

.week-stat-card {
  margin-top: 24px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(31, 38, 135, 0.37),
    0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  animation: slideInUp 0.8s ease-out;
  animation-delay: 0.5s;
}

.week-stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 
    0 12px 40px rgba(31, 38, 135, 0.5),
    0 8px 24px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background: linear-gradient(135deg, #f8f9ff 0%, #e8f0ff 100%);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
  animation: pulse 1.5s infinite;
}

/* ECharts图表样式 */
:deep(.echarts) {
  border-radius: 12px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .dashboard-container {
    padding: 16px;
  }
  
  .stat-content {
    padding: 20px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 12px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stat-info {
    text-align: center;
    margin-top: 16px;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 16px;
  }
}
</style>